<template>
	<view>
		<view class="html2canvas" :prop="renderProp" :change:prop="html2canvas.create">
			<slot></slot>
			<view class="canvas-fixed">
				<!-- <r-canvas ref="rCanvas"></r-canvas> -->
			</view>
		</view>

	</view>
</template>

<script>
	import { base64ToPath } from '@/common/sdk/image-tools.js';
	export default {
		name: 'html2canvas',
		props: {
			domId: {
				type: String,
				required: true
			}
		},
		data() {
			return {};
		},
		computed: {
			renderProp() {
				return { domId: this.domId, statusBarHeight: this.$StatusBarHeight };
			}
		},
		mounted() {

		},
		methods: {
			async renderFinish({ base64, height, width }) {
				try {
					const imgPath = await base64ToPath(base64, '.jpeg');
					this.$emit('renderFinish', { src: imgPath });
					return;
					let titleH = 48 + this.$StatusBarHeight;
					let canvasH = height + 60;
					// 初始化画布
					await this.$refs.rCanvas.init({
						canvas_id: 'rCanvas',
						canvas_width: width,
						canvas_height: canvasH,
						notCompSize: true,
						hidden: false,
					});
					// 画文章内容
					this.$refs.rCanvas.ctx.drawImage(imgPath, 0, 40, width, height);

					// 生成图片
					await this.$refs.rCanvas.draw(res => {
						this.hideLoading();
						//res.tempFilePath：生成成功，返回base64图片
						this.$emit('renderFinish', { src: res.tempFilePath, height: canvasH });
						// resolve(res.tempFilePath)
					});

					// this.$emit('renderFinish', imgPath);
				} catch (e) {
					//TODO handle the exception
					console.debug('html2canvas error', e);
				}
			},
			showLoading() {
				uni.showLoading({
					mask: true,
					title: '生成中',
				});
			},
			hideLoading() {
				setTimeout(() => {
					uni.hideLoading();
				}, 1000);
			},
			upx2px(num) {
				return uni.upx2px(num);
			},
		}
	};
</script>

<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		methods: {
			async create(prop) {
				try {
					this.$ownerInstance.callMethod('showLoading', true);
					const timeout = setTimeout(async () => {
						const shareContent = document.querySelector(prop.domId);
						const canvas = await html2canvas(shareContent, {
							width: shareContent.offsetWidth, //设置canvas尺寸与所截图尺寸相同，防止白边
							height: shareContent.offsetHeight + 140, //防止白边
							logging: true,
							useCORS: true,
							x: 0,
							y: -90,
							// dpi: window.devicePixelRatio * 100,
							// scale: 2
							// y: 48 + prop.statusBarHeight ,
						});
						const base64 = canvas.toDataURL('image/png', 1);
						this.$ownerInstance.callMethod('renderFinish', {
							base64,
							height: shareContent
								.offsetHeight,
							width: shareContent.offsetWidth
						});
						// this.$ownerInstance.callMethod('hideLoading', true);
						clearTimeout(timeout);
					}, 500);
				} catch (error) {
					console.debug(error)
				}
			}
		}
	}
</script>


<style lang="scss" scoped>
	.canvas-fixed {
		position: fixed;
		top: -10000px;
	}
</style>
